<template>
    <div class="container">
        <div class="app-container">
            <div class="left">
                <el-input v-model="keyword" @input="search" style="margin-bottom:10px" type="text"
                          prefix-icon="el-icon-search" size="small"
                          placeholder="输入员工姓名全员搜索"/>
                <el-tree
                    ref="tree"
                    :data="depts"
                    :props="defaultProps"
                    default-expand-all
                    highlight-current
                    current-node-key="1"
                    :expand-on-click-node=false
                    @node-click="handleNodeClick">
                </el-tree>
            </div>
            <div class="right">
                <el-row class="opeate-tools" type="flex" justify="end">
                    <el-button size="mini" type="primary" @click="$router.push('/employee/detail')">添加员工</el-button>
                    <el-button size="mini" @click="showUploadExcel">excel导入</el-button>
                    <el-button size="mini" @click="outerExcel" v-role="'123'">excel导出</el-button>
                </el-row>
                <template>
                    <el-table
                        :data="tableList"
                        style="width: 100%"
                    >
                        <el-table-column
                            prop="staffPhoto"
                            label="头像">
                            <template slot-scope="scope">
                                <img v-if="scope.row.staffPhoto" :src="scope.row.staffPhoto" alt="">
                                <div v-else class="username">{{ scope.row.username.charAt(0) }}</div>
                            </template>
                        </el-table-column>
                        <el-table-column
                            prop="username"
                            label="姓名">
                        </el-table-column>
                        <el-table-column
                            prop="mobile"
                            label="手机号">
                        </el-table-column>
                        <el-table-column
                            prop="workNumber"
                            sortable
                            label="工号">
                        </el-table-column>
                        <el-table-column
                            prop="formOfEmployment"
                            sortable
                            label="聘用形式">
                            <template slot-scope="scope">
                                {{ scope.row.formOfEmployment === 1 ? '正式' : '非正式' }}
                            </template>
                        </el-table-column>
                        <el-table-column
                            prop="departmentId"
                            sortable
                            label="部门">
                            <template slot-scope="scope">
                                {{
                                    evenDepts.find(e => e.id === scope.row.departmentId) ?
                                        evenDepts.find(e => e.id === scope.row.departmentId).name :
                                        ''
                                }}
                            </template>
                        </el-table-column>
                        <el-table-column
                            prop="timeOfEntry"
                            label="入职时间">
                        </el-table-column>
                        <el-table-column
                            fixed="right"
                            label="操作"
                            width="180">
                            <template slot-scope="scope">
                                <el-button @click="view(scope.row)" type="text" size="small">查看</el-button>
                                <el-button @click="role(scope.row)" type="text" size="small">角色</el-button>
                                <el-button @click="del(scope.row)" slot="reference" type="text" size="small">删除
                                </el-button>
                            </template>
                        </el-table-column>
                    </el-table>
                </template>
                <el-pagination
                    @size-change="handleSizeChange"
                    @current-change="handleCurrentChange"
                    :current-page="page"
                    :page-sizes="[5, 10, 20]"
                    :page-size="10"
                    layout="total, sizes, prev, pager, next, jumper"
                    :total="total">
                </el-pagination>
            </div>
        </div>

        <el-dialog
            title="文件上传"
            :visible.sync="showUpload"
            width="30%">
            <el-upload
                ref="upload"
                class="upload-demo"
                drag
                :show-file-list="false"
                accept=".xlsx, .xls"
                @change.native="uploadExcel"
                :auto-upload="false"
                action="">
                <i class="el-icon-upload"></i>
                <div class="el-upload__text"><em @click.stop="downloadTemplate">下载模板文件</em></div>
                <div class="el-upload__text">将文件拖到此处，或<em>点击上传</em></div>
            </el-upload>
        </el-dialog>
        <el-dialog
            title="角色分配"
            :visible.sync="showRole"
            :before-close="close"
            width="40%">
            <el-checkbox-group v-model="checkedRoles">
                <el-checkbox :label="e.id" v-for="e in roleList" :key="e.id">{{ e.name }}</el-checkbox>
            </el-checkbox-group>
            <span slot="footer" class="dialog-footer">
                <el-button size="mini" type="primary" @click="submitDialog">确 定</el-button>
                <el-button size="mini" @click="close">取 消</el-button>
            </span>
        </el-dialog>
    </div>
</template>

<script>
import { getDepartment } from '@/api/department'
import { arrToTree } from '@/utils/arrToTree'
import {
    delEmployeeItem,
    getEmployeeList,
    innerExcel,
    outerExcel,
    outerTemplate,
    getEmployeeItem,
    editEmployeeRoles
} from '@/api/employee'
import FileSaver from 'file-saver'
import { getEnableList } from '@/api/role'

export default {
    name: 'Employee',
    async created () {
        await this.getDepartment()
    },
    data () {
        return {
            showUpload: false,
            showRole: false,
            showPopover: false,
            evenDepts: [],
            depts: [],
            defaultProps: {
                label: 'name',
                children: 'children'
            },
            tableList: [],
            total: 0,
            page: 1,
            pageSize: 10,
            keyword: '',
            departmentId: 1,
            timeLock: false,
            checkedRoles: [],
            roleList: [],
            currentID: ''
        }
    },
    methods: {
        async getDepartment () {
            const res = await getDepartment()
            this.evenDepts = res.data.data
            this.depts = arrToTree(res.data.data, 0)
            this.$nextTick(() => {
                this.departmentId = this.evenDepts[0].id
                document.querySelector('.el-tree > .el-tree-node > .el-tree-node__content').click()
            })
        },
        async renderList () {
            const res = await getEmployeeList({
                page: this.page,
                pagesize: this.pageSize,
                keyword: this.keyword,
                departmentId: this.departmentId
            })
            this.total = res.data.data.total
            this.tableList = res.data.data.rows
        },
        handleNodeClick (data) {
            this.departmentId = data.id
            this.renderList()
        },
        handleSizeChange (val) {
            this.pageSize = val
            this.page = 1
            this.renderList()
        },
        handleCurrentChange (val) {
            this.page = val
            this.renderList()
        },
        view (scope) {
            this.$router.push(`/employee/detail/${scope.id}`)
        },
        async role (scope) {
            this.currentID = scope.id
            this.showRole = true
            const res = await getEnableList()
            const res2 = await getEmployeeItem(scope.id)
            this.roleList = res.data.data
            this.checkedRoles = res2.data.data.roleIds
        },
        async submitDialog () {
            const res = await editEmployeeRoles({
                id: this.currentID,
                roleIds: this.checkedRoles
            })
            if (res.data.success) this.close()
        },
        async del (scope) {
            const res = await this.$confirm('确定要删除吗？')
            if (res) {
                await delEmployeeItem(scope.id)
                if (this.tableList.length === 1 && this.page !== 1) this.page--
                await this.renderList()
            }
        },
        async search () {
            if (!this.timeLock) {
                this.timeLock = true
                setTimeout(() => {
                    this.timeLock = false
                }, 500)
            }
        },
        async outerExcel () {
            const res = await outerExcel()
            FileSaver.saveAs(res, '员工信息表.xlsx')
        },
        showUploadExcel () {
            this.showUpload = true
        },
        async downloadTemplate () {
            const res = await outerTemplate()
            FileSaver.saveAs(res, '员工信息表-模板.xlsx')
        },
        async uploadExcel (e) {
            if (e.target.files.length >= 1) {
                const data = new FormData
                data.append('file', e.target.files[0])
                await innerExcel(data)
            }
        },
        close () {
            this.showRole = false
            this.roleList = []
        }
    }
}
</script>

<style lang="scss" scoped>
.app-container {
    background: #FFFFFF;
    display: flex;

    .left {
        width: 280px;
        padding: 20px;
        border-right: 1px solid #EAEEF4;
    }

    .right {
        flex: 1;
        padding: 20px;

        .opeate-tools {
            margin: 10px;
        }

        .username {
            height: 30px;
            width: 30px;
            line-height: 30px;
            text-align: center;
            border-radius: 50%;
            color: #FFFFFF;
            background: #04C9BE;
            font-size: 12px;
            display: inline-block;
        }

        ::v-deep .el-table {
            img {
                width: 30px;
                height: 30px;
                border-radius: 15px;
            }
        }
    }
}

.container {
    ::v-deep .upload-demo {

        .el-upload {
            width: 100%;

            .el-upload-dragger {
                width: 100%;

                .el-upload__text {
                    margin: 12px 0;
                }
            }


        }


    }
}

</style>
